#!/usr/bin/env python3
"""
Git LFS 管理面板 - Flask 后端
提供 Git LFS 相关功能的 REST API
"""

import os
import subprocess
import json
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

def run_git_command(command):
    """执行 git 命令并返回结果"""
    try:
        result = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            cwd=os.getcwd()
        )
        return {
            'success': result.returncode == 0,
            'stdout': result.stdout.strip(),
            'stderr': result.stderr.strip(),
            'returncode': result.returncode
        }
    except Exception as e:
        return {
            'success': False,
            'stdout': '',
            'stderr': str(e),
            'returncode': -1
        }

@app.route('/')
def index():
    """渲染主页"""
    return render_template('index.html')

@app.route('/api/lfs/install', methods=['POST'])
def lfs_install():
    """执行 git lfs install"""
    result = run_git_command('git lfs install')
    return jsonify(result)

@app.route('/api/lfs/track', methods=['POST'])
def lfs_track():
    """添加 LFS 追踪规则"""
    data = request.json
    pattern = data.get('pattern', '')
    if not pattern:
        return jsonify({'success': False, 'error': 'Pattern is required'})
    
    command = f'git lfs track "{pattern}"'
    result = run_git_command(command)
    return jsonify(result)

@app.route('/api/lfs/untrack', methods=['POST'])
def lfs_untrack():
    """移除 LFS 追踪规则"""
    data = request.json
    pattern = data.get('pattern', '')
    if not pattern:
        return jsonify({'success': False, 'error': 'Pattern is required'})
    
    command = f'git lfs untrack "{pattern}"'
    result = run_git_command(command)
    return jsonify(result)

@app.route('/api/lfs/tracked', methods=['GET'])
def lfs_tracked():
    """获取已追踪的文件类型"""
    gitattributes_path = '.gitattributes'
    tracked_files = []
    
    if os.path.exists(gitattributes_path):
        try:
            with open(gitattributes_path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line and 'filter=lfs' in line:
                        parts = line.split()
                        if len(parts) >= 2:
                            pattern = parts[0]
                            size_info = get_file_size_info(pattern)
                            tracked_files.append({
                                'pattern': pattern,
                                'size': size_info
                            })
        except Exception as e:
            return jsonify({'success': False, 'error': str(e)})
    
    return jsonify({'success': True, 'data': tracked_files})

def get_file_size_info(pattern):
    """获取匹配文件的总大小信息"""
    try:
        # 使用 git ls-files 和 du 来获取文件大小
        command = f"git ls-files | grep -E '{pattern.replace('*', '.*')}' | xargs -I {{}} du -ch {{}} 2>/dev/null | tail -1"
        result = run_git_command(command)
        if result['success'] and result['stdout']:
            return result['stdout'].split()[0]
        return 'N/A'
    except:
        return 'N/A'

@app.route('/api/lfs/status', methods=['GET'])
def lfs_status():
    """获取 LFS 状态"""
    result = run_git_command('git lfs status')
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
